package cn.ctyun.ipush.dao;

import cn.ctyun.ipush.model.*;
import cn.ctyun.ipush.utils.ConfigUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.vo.TaskVo;
import cn.ctyun.ipush.web.user.bo.City;
import cn.ctyun.ipush.web.user.bo.UserModel;
import com.alibaba.fastjson.JSON;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.JdbcDao;
import com.dexcoder.dal.build.Criteria;
import com.dexcoder.dal.spring.page.PageControl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-6-16
 * Time: 上午11:22
 * To change this template use File | Settings | File Templates.
 */
@Component
public class TaskDao {

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(TaskDao.class);

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private TaskDetailDao taskDetailDao;

    @Autowired
    private PageControl pageControl;

    /**
     * task 任务保存，其中，dataSource/excel/email/picture/yixin 都需要新建
     *
     * @param taskVo
     * @return
     */
//    public boolean insert(TaskVo taskVo) {
//        //add model primary key
//        TaskModel tm = new TaskModel();
//        tm.setTaskModelId(UUIDUtils.getUUID32());
//        tm.setTaskDetailId(UUIDUtils.getUUID32());
//        tm.setExcelId(UUIDUtils.getUUID32());
//        tm.setDataSourceId(UUIDUtils.getUUID32());
//        tm.setEmailId(UUIDUtils.getUUID32());
//        tm.setPictureId(UUIDUtils.getUUID32());
//        tm.setYixinId(UUIDUtils.getUUID32());
//
//        TaskDetailModel taskDetailModel = taskVo.getTaskDetail();
//        taskDetailModel.setTaskDetailModelId(tm.getTaskDetailId());
//        taskDetailModel.setTaskGroupName(taskDetailModel.getTaskGroupName());
//        taskDetailModel.setCronExpression(taskDetailModel.getCronExpression());
//        taskDetailModel.setTaskName(taskDetailModel.getTaskGroupName() + "_" + "task_" + DateUtils.timestampToDataString(System.currentTimeMillis()));
//        taskDetailModel.setCreateDate(DateUtils.dateToString(new Date()));
//        taskDetailModel.setIsAutoRun("1");
//        taskDetailModel.setIsDeleted("0");
//
//        DataSourceModel dataSourceModel = taskVo.getDataSource();
//        dataSourceModel.setDataSourceModelId(tm.getDataSourceId());
//        dataSourceModel.setConnMaxCount("5");//现在无意义 现在是每一个时间点是一个连接
//        dataSourceModel.setCreateDate(DateUtils.dateToString(new Date()));
//        dataSourceModel.setIsDeleted("0");
//
//
//        taskVo.getTaskDetail().setTaskDetailModelId(tm.getTaskDetailId());
//        taskVo.getDataSource().setDataSourceModelId(tm.getDataSourceId());
//        taskVo.getExcel().setExcelModelId(tm.getExcelId());
//        taskVo.getPicture().setPictureModelId(tm.getPictureId());
//        taskVo.getEmail().setEmailModelId(tm.getEmailId());
//        taskVo.getYixin().setYixinModelId(tm.getYixinId());
//
//        //系统定的字段值
//        // taskVo.getTaskDetail().setTaskName();
//
//        try {
//            jdbcDao.save(tm);
//            jdbcDao.save(dataSourceModel);
//            jdbcDao.save(taskDetailModel);
//            jdbcDao.save(taskVo.getExcel());
//            jdbcDao.save(taskVo.getPicture());
//            jdbcDao.save(taskVo.getEmail());
//            jdbcDao.save(taskVo.getYixin());
//            LOG.info("task : " + JSON.toJSONString(tm) + " save success");
//            return true;
//        } catch (Exception ex) {
//            return false;
//        }
//    }

    /**
     * task 任务保存，其中，dataSource/excel/email/picture/yixin 主键id都存在
     *
     * @param taskVo
     */
    public boolean insert(TaskVo taskVo) {
        //add model primary key
        TaskModel tm = taskVo.getTargetObject(TaskModel.class);
        tm.setTaskModelId(UUIDUtils.getUUID32());
        tm.setTaskDetailId(UUIDUtils.getUUID32());
        tm.setCreateDate(DateUtils.dateToString(new Date()));


        taskVo.setTaskModelId(tm.getTaskModelId());
        taskVo.setTaskDetailId(tm.getTaskDetailId());

        TaskDetailModel taskDetailModel = taskVo.getTaskDetail();
        taskDetailModel.setTaskDetailModelId(tm.getTaskDetailId());
        taskDetailModel.setTaskName("task_" + DateUtils.timestampToDataString(System.currentTimeMillis()));
        taskDetailModel.setCreateDate(DateUtils.dateToString(new Date()));
        taskDetailModel.setCreateUserid(tm.getCreateUserid());
        taskDetailModel.setIsDeleted("0");

        try {
            jdbcDao.save(tm);
            taskDetailDao.save(taskDetailModel);
            LOG.info("task : " + JSON.toJSONString(tm) + " save success");
            return true;
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return false;
        }
    }

    /**
     * 更新任务task
     *
     * @param taskModel
     * @return
     */
    public int update(TaskModel taskModel) {
        if (taskModel.getTaskDetailId() == null) {
            LOG.info("Error taskModel id 更新不能为空");
            return 0;
        }
        taskModel.setModifyDate(DateUtils.dateToString(new Date()));
        return jdbcDao.update(taskModel);
    }

    /**
     * @param taskModelId
     * @return
     */
    public int delete(String taskModelId) {
        if (StringUtils.isEmpty(taskModelId)) {
            LOG.info("Error taskModel id 更新不能为空");
            return 0;
        }
        Criteria criteria = Criteria.update(TaskModel.class).set("isDeleted", "1").where("taskModelId", new Object[]{taskModelId});
        return jdbcDao.update(criteria);
    }

    public TaskModel querySingleResult(TaskModel taskModel) {
        return jdbcDao.querySingleResult(taskModel);
    }

    //查询全部
    public List<TaskModel> queryList() {
        return jdbcDao.queryList(Criteria.select(TaskModel.class).where("isDeleted", new Object[]{"0"}));
    }

    //模糊条件查询
    public List<TaskModel> queryList(Criteria criteria) {
        return jdbcDao.queryList(criteria);
    }

    //精确条件查询
    public List<TaskModel> queryList(TaskModel taskModel) {
        taskModel.setIsDeleted("0");
        return jdbcDao.queryList(taskModel);
    }

    /**
     * @param taskModel 完整的taskModel 数据库对象
     * @return
     */
    public TaskVo getTaskVoByTaskModel(TaskModel taskModel) {

        TaskVo taskVo = new TaskVo();

        //v1.1
        taskVo.setIsSendExcel(taskModel.getIsSendExcel());
        taskVo.setIsSendPicture(taskModel.getIsSendPicture());
        taskVo.setIsSendEmail(taskModel.getIsSendEmail());
        taskVo.setIsSendYixin(taskModel.getIsSendYixin());
        taskVo.setEmailContent(taskModel.getEmailContent()==null?"":taskModel.getEmailContent());
        taskVo.setEmailSubject(taskModel.getEmailSubject()==null?"":taskModel.getEmailSubject());
        taskVo.setYixinReceivers(taskModel.getYixinReceivers()==null?"":taskModel.getYixinReceivers());
        //v1.1

        taskVo.setTaskDetailId(taskModel.getTaskDetailId());
        taskVo.setDataSourceId(taskModel.getDataSourceId());
        taskVo.setExcelId(taskModel.getExcelId());
        taskVo.setPictureId(taskModel.getPictureId());
        taskVo.setEmailId(taskModel.getEmailId());
        taskVo.setYixinId(taskModel.getYixinId());
        taskVo.setTaskModelId(taskModel.getTaskModelId());
        taskVo.setCreateUserid(taskModel.getCreateUserid());
        taskVo.setTaskType(taskModel.getTaskType());

        DataSourceModel dataSourceModel = new DataSourceModel();
        dataSourceModel.setDataSourceModelId(taskModel.getDataSourceId());
        dataSourceModel.setIsDeleted("0");
        dataSourceModel.setCreateUserid(taskModel.getCreateUserid());

        TaskDetailModel taskDetailModel = new TaskDetailModel();
        taskDetailModel.setTaskDetailModelId(taskModel.getTaskDetailId());
        dataSourceModel.setIsDeleted("0");
        dataSourceModel.setCreateUserid(taskModel.getCreateUserid());

        ExcelModel excelModel = new ExcelModel();
        excelModel.setExcelModelId(taskModel.getExcelId());
        dataSourceModel.setIsDeleted("0");
        dataSourceModel.setCreateUserid(taskModel.getCreateUserid());

        PictureModel pictureModel = new PictureModel();
        pictureModel.setPictureModelId(taskModel.getPictureId());
        dataSourceModel.setIsDeleted("0");
        dataSourceModel.setCreateUserid(taskModel.getCreateUserid());

        EmailModel emailModel = new EmailModel();
        emailModel.setEmailModelId(taskModel.getEmailId());
        dataSourceModel.setIsDeleted("0");
        dataSourceModel.setCreateUserid(taskModel.getCreateUserid());

        YixinModel yixinModel = new YixinModel();
        yixinModel.setYixinModelId(taskModel.getYixinId());
        dataSourceModel.setIsDeleted("0");
        dataSourceModel.setCreateUserid(taskModel.getCreateUserid());

        try {

            dataSourceModel = jdbcDao.querySingleResult(dataSourceModel);
            taskDetailModel = jdbcDao.querySingleResult(taskDetailModel);
            excelModel = jdbcDao.querySingleResult(excelModel);
            pictureModel = jdbcDao.querySingleResult(pictureModel);
            emailModel = jdbcDao.querySingleResult(emailModel);
            yixinModel = jdbcDao.querySingleResult(yixinModel);

            taskVo.setDataSource(dataSourceModel);
            taskVo.setTaskDetail(taskDetailModel);
            taskVo.setExcel(excelModel);
            taskVo.setPicture(pictureModel);
            taskVo.setEmail(emailModel);
            taskVo.setYixin(yixinModel);
            return taskVo;

        } catch (Exception ex) {
            LOG.info("taskModel convert taskVo fail");
            return null;
        }

    }

    /**
     * @param taskVo 前端转换的task视图
     * @return 返回完整的taskVo对象
     */
    public TaskVo getNewTaskVoFromTaskVo(TaskVo taskVo) {

        if (taskVo.getTaskModelId() == null || taskVo.getTaskDetailId() == null || taskVo.getDataSourceId() == null || taskVo.getYixinId() == null || taskVo.getEmailId() == null || taskVo.getPictureId() == null || taskVo.getExcelId() == null)
            LOG.info("taskVo 不完整 ");

        DataSourceModel dataSourceModel = new DataSourceModel();
        dataSourceModel.setDataSourceModelId(taskVo.getDataSourceId());
        dataSourceModel = jdbcDao.querySingleResult(dataSourceModel);
        taskVo.setDataSource(dataSourceModel);

        ExcelModel excelModel = new ExcelModel();
        excelModel.setExcelModelId(taskVo.getExcelId());
        excelModel = jdbcDao.querySingleResult(excelModel);
        taskVo.setExcel(excelModel);

        EmailModel emailModel = new EmailModel();
        emailModel.setEmailModelId(taskVo.getEmailId());
        emailModel = jdbcDao.querySingleResult(emailModel);
        taskVo.setEmail(emailModel);

        PictureModel pictureModel = new PictureModel();
        pictureModel.setPictureModelId(taskVo.getPictureId());
        pictureModel = jdbcDao.querySingleResult(pictureModel);
        taskVo.setPicture(pictureModel);

        YixinModel yixinModel = new YixinModel();
        yixinModel.setYixinModelId(taskVo.getYixinId());
        yixinModel = jdbcDao.querySingleResult(yixinModel);
        taskVo.setYixin(yixinModel);

        return taskVo;


    }

    /**
     * 根据taskID 得到TaskVo
     *
     * @param taskId
     * @return
     */
    public TaskVo getDbTaskVoByTaskId(String taskId) {
        Criteria criteria = Criteria.select(TaskModel.class).where("taskModelId", new Object[]{taskId});
        TaskModel taskModel = jdbcDao.querySingleResult(criteria);
        return getTaskVoByTaskModel(taskModel);
    }

    /**
     * 数据源是否在task中存在，判断数据源删除的条件
     *
     * @param dataSourceId
     * @return
     */
    public boolean isExistDataSourceInTask(String dataSourceId) {
        Criteria criteria = Criteria.select(TaskModel.class).where("dataSourceId", new Object[]{dataSourceId}).where(" and isDeleted",new Object[]{"0"});
        int count = jdbcDao.queryCount(criteria);
        if (count < 1) {
            return false;
        }
        return true;
    }

    /**
     * 邮箱是否在task中存在，判断邮箱删除的条件
     *
     * @param emailId
     * @return
     */
    public boolean isExistEmailInTask(String emailId) {
        Criteria criteria = Criteria.select(TaskModel.class).where("emailId", new Object[]{emailId}).where(" and isDeleted",new Object[]{"0"});
        int count = jdbcDao.queryCount(criteria);
        if (count < 1) {
            return false;
        }
        return true;
    }

    public boolean isExistExcelInTask(String excelId) {
        Criteria criteria = Criteria.select(TaskModel.class).where("excelId", new Object[]{excelId}).where(" and isDeleted",new Object[]{"0"});
        int count = jdbcDao.queryCount(criteria);
        if (count < 1) {
            return false;
        }
        return true;
    }

    public boolean isExistPictureInTask(String pictureId) {
        Criteria criteria = Criteria.select(TaskModel.class).where("pictureId", new Object[]{pictureId}).where(" and isDeleted",new Object[]{"0"});
        int count = jdbcDao.queryCount(criteria);
        if (count < 1) {
            return false;
        }
        return true;
    }

    /**
     * 精确分页查询
     *
     * @param currentPage
     * @param itemPages
     * @param taskVo
     * @return
     */
    public List<TaskModel> queryListByPage(int currentPage, int itemPages, TaskVo taskVo) {
        pageControl.performPage(currentPage, itemPages);
        TaskModel taskModel = taskVo.getTargetObject(TaskModel.class);
        taskModel.setIsDeleted("0");
        // Criteria criteria = Criteria.select(TaskModel.class).where("isDeleted", new Object[]{"0"}).where(" and createUserid",new Object[]{taskVo.getCreateUserid()});
        jdbcDao.queryList(taskModel);
        return pageControl.getPager().getList(TaskModel.class);
    }

    public Object querySingleResultByName(String taskModelName) {
        if (StringUtils.isEmpty(taskModelName))
            throw new RuntimeException("taskModelName 为空");
        Criteria criteria = Criteria.select(TaskModel.class).where("taskModelName", new Object[]{taskModelName}).where("and isDeleted", new Object[]{"0"});
        return jdbcDao.querySingleResult(criteria);
    }

    //根据taskType与配置的tpye判断是否一致，决定启动任务与否
    public boolean isStartTask(TaskVo taskVo) {
        String belongType = ConfigUtils.getStringValue("startTaskBelongType");
        String currentTaskType = taskVo.getTaskType();
        if(belongType.contentEquals(currentTaskType)){
            return true;
        }else{
            return false;
        }
//        String userId=taskVo.getCreateUserid();
//        UserModel userModel=new UserModel();
//        userModel.setUserModelId(userId);
//        userModel=jdbcDao.querySingleResult(userModel);
//        if(null!=userModel){
//            City city=new City();
//            city.setCityId(userModel.getCity());
//            city=jdbcDao.querySingleResult(city);
//            String belong_type=city.getBelongType();
//            String belongType=ConfigUtils.getStringValue("startTaskBelongType");
//            String[] belongTypes=belongType.split(",");
//            for(String tmpType:belongTypes){
//                if(tmpType.contentEquals(belong_type)){
//                    return true;
//                }
//            }
//        }
       // return false;  //To change body of created methods use File | Settings | File Templates.
    }
}
